package com.tbynet.jwp.admin.option;

import java.util.ArrayList;
import java.util.List;

import com.jfinal.aop.Inject;
import com.jfinal.kit.Ret;
import com.jfinal.kit.StrKit;
import com.tbynet.jwp.admin.AdminController;
import com.tbynet.jwp.service.spi.OptionManager;
import com.tbynet.jwp.model.Options;
import com.tbynet.jwp.repository.spi.OptionService;

/**
 * 选项管理控制器
 * @ClassName: OptionAdminController
 * @Description: 负责系统选项的设置和管理
 * @Author: 佰亿互联
 * @Date: 2025年11月4日
 *
 * @Copyright: 2025 www.tbynet.com Inc. All rights reserved.
 * 注意: 本内容仅限于内部传阅，禁止外泄以及用于其他的商业目
 */
public class OptionAdminController extends AdminController {

    @Inject
    private OptionService optionService;

    @Inject
    private OptionManager optionManager;

    /**
     * 选项管理首页
     */
    public void index() {
        render("index.html");
    }

    /**
     * 常规设置
     */
    public void general() {
        if (isGet()) {
            // 获取常规设置相关选项
            String[] names = {
                    Options.blogname, Options.blogdescription, Options.siteurl,
                    Options.home, Options.new_admin_email, Options.users_can_register,
                    Options.default_role, Options.WPLANG, Options.timezone_string,
                    Options.date_format, Options.time_format, Options.start_of_week,
                    Options.zh_cn_l10n_icp_num
            };

            setOptionsToView(names);
            render("general.html");
            return;
        }

        // POST请求：保存常规设置
        List<Options> options = new ArrayList<>();

        // 构建选项列表
        buildGeneralOptions(options);

        // 使用Manager层进行批量更新（包含事务）
        Ret result = optionManager.batchUpdateOptions(options);

        if (result.isOk()) {
            ok(result);
        } else {
            fail(result.getStr("msg"));
        }
    }

    /**
     * 撰写设置
     */
    public void writing() {
        if (isGet()) {
            String[] names = {
                    Options.default_category, Options.default_post_format, Options.mailserver_url,
                    Options.mailserver_port, Options.mailserver_login, Options.mailserver_pass,
                    Options.default_email_category, Options.ping_sites
            };

            setOptionsToView(names);
            render("writing.html");
            return;
        }

        List<Options> options = new ArrayList<>();
        buildWritingOptions(options);

        Ret result = optionManager.batchUpdateOptions(options);
        handleSaveResult(result);
    }

    /**
     * 阅读设置
     */
    public void reading() {
        if (isGet()) {
            String[] names = {
                    Options.show_on_front, Options.page_on_front, Options.page_for_posts,
                    Options.posts_per_page, Options.posts_per_rss, Options.rss_use_excerpt,
                    Options.blog_public
            };

            setOptionsToView(names);
            render("reading.html");
            return;
        }

        List<Options> options = new ArrayList<>();
        buildReadingOptions(options);

        Ret result = optionManager.batchUpdateOptions(options);
        handleSaveResult(result);
    }

    public void discussion() {
        if(isGet()) {
            String[] names = {Options.default_pingback_flag, Options.default_ping_status, Options.default_comment_status,
                    Options.require_name_email, Options.comment_registration, Options.close_comments_for_old_posts,
                    Options.close_comments_days_old, Options.show_comments_cookies_opt_in, Options.thread_comments,
                    Options.thread_comments_depth, Options.page_comments, Options.comments_per_page, Options.default_comments_page,
                    Options.comment_order, Options.comments_notify, Options.moderation_notify, Options.comment_moderation,
                    Options.comment_whitelist, Options.comment_max_links, Options.moderation_keys, Options.blacklist_keys,
                    Options.show_avatars, Options.avatar_rating, Options.avatar_default};

            setOptionsToView(names);
            render("discussion.html");
            return;
        }

        List<Options> options = new ArrayList<Options>();
        buildDisussionOptions(options);

        Ret result = optionManager.batchUpdateOptions(options);
        handleSaveResult(result);
    }



    public void media() {
        if(isGet()) {
            String[] names = {Options.thumbnail_size_w, Options.thumbnail_size_h, Options.thumbnail_crop,
                    Options.medium_size_w, Options.medium_size_h, Options.large_size_w, Options.large_size_h,
                    Options.uploads_use_yearmonth_folders};

            setOptionsToView(names);
            render("media.html");
            return;
        }

        List<Options> options = new ArrayList<Options>();
        buildMediaOptions(options);

        Ret result = optionManager.batchUpdateOptions(options);
        handleSaveResult(result);
    }

    public void permalink() {
        if(isGet()) {
            String[] names = {Options.permalink_structure, Options.category_base, Options.tag_base};

            setOptionsToView(names);
            render("permalink.html");
            return;
        }

        List<Options> options = new ArrayList<Options>();
        buildPermalinkOptions(options);

        Ret result = optionManager.batchUpdateOptions(options);
        handleSaveResult(result);
    }


    public void privacy() {
        if(isGet()) {
            String[] names = {Options.wp_page_for_privacy_policy};

            setOptionsToView(names);
            render("privacy.html");
            return;
        }

        List<Options> options = new ArrayList<Options>();
        buildPrivacyOptions(options);

        Ret result = optionManager.batchUpdateOptions(options);
        handleSaveResult(result);
    }

    // ============ 私有方法 ============

    /**
     * 将选项设置到视图
     */
    private void setOptionsToView(String[] optionNames) {
        List<Options> options = optionService.getOptions(optionNames);
        for (Options option : options) {
            if (option != null && option.getOptionValue() != null) {
                set(option.getOptionName(), option.getOptionValue());
            }
        }
    }

    /**
     * 构建常规设置选项
     */
    private void buildGeneralOptions(List<Options> options) {
        addOptionToList(options, Options.blogname, getPara("blogname", ""));
        addOptionToList(options, Options.blogdescription, getPara("blogdescription", ""));
        addOptionToList(options, Options.siteurl, getPara("siteurl", ""));
        addOptionToList(options, Options.home, getPara("home", ""));
        addOptionToList(options, Options.new_admin_email, getPara("new_admin_email", ""));
        addOptionToList(options, Options.users_can_register, getPara("users_can_register", "0"));
        addOptionToList(options, Options.default_role, getPara("default_role"));
        addOptionToList(options, Options.WPLANG, getPara("WPLANG"));
        addOptionToList(options, Options.timezone_string, getPara("timezone_string"));
        addOptionToList(options, Options.date_format, getPara("date_format_custom", ""));
        addOptionToList(options, Options.time_format, getPara("time_format_custom", ""));
        addOptionToList(options, Options.start_of_week, getPara("start_of_week"));
        addOptionToList(options, Options.zh_cn_l10n_icp_num, getPara("zh_cn_l10n_icp_num", ""));
    }

    /**
     * 构建撰写设置选项
     */
    private void buildWritingOptions(List<Options> options) {
        addOptionToList(options, Options.default_category, getPara("default_category"));
        addOptionToList(options, Options.default_post_format, getPara("default_post_format"));
        addOptionToList(options, Options.mailserver_url, getPara("mailserver_url", ""));
        addOptionToList(options, Options.mailserver_port, getPara("mailserver_port", ""));
        addOptionToList(options, Options.mailserver_login, getPara("mailserver_login", ""));
        addOptionToList(options, Options.mailserver_pass, getPara("mailserver_pass", ""));
        addOptionToList(options, Options.default_email_category, getPara("default_email_category"));
        addOptionToList(options, Options.ping_sites, getPara("ping_sites", ""));
    }

    /**
     * 构建阅读设置选项
     */
    private void buildReadingOptions(List<Options> options) {
        addOptionToList(options, Options.show_on_front, getPara("show_on_front"));
        addOptionToList(options, Options.page_on_front, getPara("page_on_front"));
        addOptionToList(options, Options.page_for_posts, getPara("page_for_posts"));
        addOptionToList(options, Options.posts_per_page, getPara("posts_per_page", "10"));
        addOptionToList(options, Options.posts_per_rss, getPara("posts_per_rss", "10"));
        addOptionToList(options, Options.rss_use_excerpt, getPara("rss_use_excerpt"));
        addOptionToList(options, Options.blog_public, getPara("blog_public"));
    }

    private void buildDisussionOptions(List<Options> options) {
        addOptionToList(options, Options.default_pingback_flag, getPara("default_pingback_flag", "0"));
        addOptionToList(options, Options.default_ping_status, getPara("default_ping_status", "closed"));
        addOptionToList(options, Options.default_comment_status, getPara("default_comment_status", "closed"));
        addOptionToList(options, Options.require_name_email, getPara("require_name_email", "0"));
        addOptionToList(options, Options.comment_registration, getPara("comment_registration", "0"));
        addOptionToList(options, Options.close_comments_for_old_posts, getPara("close_comments_for_old_posts", "0"));
        addOptionToList(options, Options.close_comments_days_old, getPara("close_comments_days_old", "0"));
        addOptionToList(options, Options.show_comments_cookies_opt_in, getPara("show_comments_cookies_opt_in", "0"));
        addOptionToList(options, Options.thread_comments, getPara("thread_comments", "0"));
        addOptionToList(options, Options.thread_comments_depth, getPara("thread_comments_depth"));
        addOptionToList(options, Options.page_comments, getPara("page_comments", "0"));
        addOptionToList(options, Options.comments_per_page, getPara("comments_per_page", "0"));
        addOptionToList(options, Options.default_comments_page, getPara("default_comments_page"));
        addOptionToList(options, Options.comment_order, getPara("comment_order"));
        addOptionToList(options, Options.comments_notify, getPara("comments_notify", "0"));
        addOptionToList(options, Options.moderation_notify, getPara("moderation_notify", "0"));
        addOptionToList(options, Options.comment_moderation, getPara("comment_moderation", "0"));
        addOptionToList(options, Options.comment_whitelist, getPara("comment_whitelist", "0"));
        addOptionToList(options, Options.comment_max_links, getPara("comment_max_links", "0"));
        addOptionToList(options, Options.moderation_keys, getPara("moderation_keys", ""));
        addOptionToList(options, Options.blacklist_keys, getPara("blacklist_keys", ""));
        addOptionToList(options, Options.show_avatars, getPara("show_avatars", "0"));
        addOptionToList(options, Options.avatar_rating, getPara("avatar_rating"));
        addOptionToList(options, Options.avatar_default, getPara("avatar_default"));
    }

    private void buildMediaOptions(List<Options> options) {
        addOptionToList(options, Options.thumbnail_size_w, getPara("thumbnail_size_w", "0"));
        addOptionToList(options, Options.thumbnail_size_h, getPara("thumbnail_size_h", "0"));
        addOptionToList(options, Options.thumbnail_crop, getPara("thumbnail_crop", "0"));
        addOptionToList(options, Options.medium_size_w, getPara("medium_size_w", "0"));
        addOptionToList(options, Options.medium_size_h, getPara("medium_size_h", "0"));
        addOptionToList(options, Options.large_size_w, getPara("large_size_w", "0"));
        addOptionToList(options, Options.large_size_h, getPara("large_size_h", "0"));
        addOptionToList(options, Options.uploads_use_yearmonth_folders, getPara("uploads_use_yearmonth_folders", "0"));
    }

    private void buildPermalinkOptions(List<Options> options) {
        addOptionToList(options, Options.permalink_structure, getPara("permalink_structure", ""));
        addOptionToList(options, Options.category_base, getPara("category_base", ""));
        addOptionToList(options, Options.tag_base, getPara("tag_base", ""));
    }

    private void buildPrivacyOptions(List<Options> options) {
        addOptionToList(options, Options.wp_page_for_privacy_policy, getPara("page_for_privacy_policy", ""));
    }

    /**
     * 添加选项到列表
     */
    private void addOptionToList(List<Options> options, String optionName, String optionValue) {
        if (StrKit.notBlank(optionValue)) {
            Options option = optionService.getOption(optionName);
            if (option == null) {
                option = new Options();
                option.setOptionName(optionName);
                option.setAutoload("yes");
            }
            option.setOptionValue(optionValue);
            options.add(option);
        }
    }

    /**
     * 处理保存结果
     */
    private void handleSaveResult(Ret result) {
        if (result.isOk()) {
            ok(result);
        } else {
            fail(result.getStr("msg"));
        }
    }
}